# -*- coding: utf-8 -*-
import datetime
import math
import scrapy
import re

import sys
import os

# 添加项目根目录到Python路径
current_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, current_dir)

from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item, urllib, time, urljoin, json, urlencode
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class FujianZfxxgkPolicy(BaseTaxPolicySpider):
    name = 'fujian_ningde_was_policy'

    province = '福建省'
    city = '宁德市'
    # county = ''
    park = ''
    page_size = int(26 * 1.5)
    custom_settings = {
        "DEFAULT_REQUEST_HEADERS": {
            'Accept': 'application/json, text/javascript, */*; q=0.01',
            'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
            'Accept-Encoding': 'gzip, deflate',
            'Cache-Control': 'no-cache',
            'Connection': 'keep-alive',
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'Origin': 'http://www.jiaocheng.gov.cn',
            'Pragma': 'no-cache',
            'Referer': 'http://www.jiaocheng.gov.cn/zfxxgkzl/zfxxgkml/qzfxxgkml/?type=1',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
            'X-Requested-With': 'XMLHttpRequest',
            'sec-ch-ua': '"Not_A Brand";v="8", "Chromium";v="120", "Google Chrome";v="120"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"Windows"',
            'sec-fetch-dest': 'empty',
            'sec-fetch-mode': 'cors',
            'sec-fetch-site': 'same-origin',
        }
    }

    def __init__(self, get_next=False, **kwargs):
        super().__init__(**kwargs)
        print(get_next)
        self.get_next = get_next
        self.cookies = {
            'HttpOnly': ''
        }

    @classmethod
    def update_settings(cls, settings) -> None:
        downloader_middlewares = settings.getdict("DOWNLOADER_MIDDLEWARES")
        new_settings = {
            **(cls.custom_settings or {}),
            **{
                "COOKIES_ENABLED": True,
                "DOWNLOAD_TIMEOUT": 200,
                # "CONCURRENT_REQUESTS": 5,
                "HTTPERROR_ALLOWED_CODES": [302, 400, 404, 407, 500, 200, 202, 502, 429, 521, 403],
                # "DOWNLOAD_DELAY": 5,
                # "DOWNLOADER_MIDDLEWARES": {
                #     "components.middlewares.downloadmiddlewares.public.useragent_random.RandomUserAgentMiddleware": None,
                #     "components.middlewares.downloadmiddlewares.public.company_ip_by_api.CompanyIpByApiMiddleware": None,
                #     "components.middlewares.downloadmiddlewares.public.error_collector.ErrorCollectorMiddleware": None,
                #     # **downloader_middlewares
                # }
            },
        }
        settings.setdict(new_settings or {}, priority="spider")

    def start_requests(self):
        for source, county, url, channelid, classsql in [
            ["宁德市蕉城区发展和改革局", "蕉城区", "http://www.jiaocheng.gov.cn/zfxxgkzl/zfxxgkml/zfgbmxxgk/jcqfzhggj/gkml/qtyzdgkdzfxx/", "239509", "chnlid=24045*modal=1"],
            ["宁德市蕉城区工信局", "蕉城区", "http://www.jiaocheng.gov.cn/zfxxgkzl/zfxxgkml/zfgbmxxgk/jcqgxj/gkml/gzdt/", "239509", "chnlid=24017*modal=1"],
            ["宁德市蕉城区财政局", "蕉城区", "http://www.jiaocheng.gov.cn/zfxxgkzl/zfxxgkml/zfgbmxxgk/jcqczj/gkml/qjczgfxwj/", "239509", "chnlid=24011*modal=1"],
            ["宁德市蕉城区人社局", "蕉城区", "http://www.jiaocheng.gov.cn/zfxxgkzl/zfxxgkml/zfgbmxxgk/jcqgxj/gkml/gzdt/", "239509", "chnlid=23969*modal=1"],
            ["宁德市蕉城区自然资源局", "蕉城区", "http://www.jiaocheng.gov.cn/zfxxgkzl/zfxxgkml/zfgbmxxgk/jcqzrzyj/gkml/zdgkzfxx/", "239509", "chnlid=24050*modal=1"],
            ["宁德市蕉城区农业农村局", "蕉城区", "http://www.jiaocheng.gov.cn/zfxxgkzl/zfxxgkml/zfgbmxxgk/jcqnyncj/gkml/tzwj/", "239509", "chnlid=24076*modal=1"],
            ["宁德市蕉城区商务局", "蕉城区", "http://www.jiaocheng.gov.cn/zfxxgkzl/zfxxgkml/zfgbmxxgk/jcqswj/gkml/gzdt/", "239509", "chnlid=24040*modal=1"],
            ["宁德市蕉城区市场监督管理局", "蕉城区", "http://www.jiaocheng.gov.cn/zfxxgkzl/zfxxgkml/zfgbmxxgk/jcqscjdglj/gkml/xxgk/", "239509", "chnlid=24083*modal=1"],
        ]:
            data = {
                'sortfield': '-pubdate',
                'channelid': channelid,
                'classsql': classsql,
                # 'classnum': str(100),
                # 'classsort': str(0),
                'templet': 'docswj.jsp',
                'prepage': str(50),
                'page': str(1),
            }
            temp_url = urljoin(url, '/was5/web/search')
            meta = {"item": {'source': source, 'county': county}}
            meta.update({
                "data": data,
            })
            print(data)
            yield self.FormRequest(
                temp_url,
                formdata=data,
                method="POST",
                # cookies=self.cookies,
                callback=self.parse_list,
                dont_filter=True,
                meta=meta
            )

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        meta = response.meta
        print(response.text)
        data = json.loads(response.text.replace('\n', ''))
        url_list = data['docs']
        for elem in url_list:
            if elem.get('url') == '链接':
                continue
            item = Item()
            item['source_url'] = elem['docpuburl']
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem['pubdate'].replace("年", "-").replace("月", "-")[:-1]
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            print(item['publish_date'], response.url, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        page = meta.get('page', 1)
        if meta.get("is_next") is False:
            return
        total_page = math.ceil(int(data['count']) / 50)
        print(meta['data'], page, "total_page", total_page)
        meta['is_next'] = False
        for page in list(range(2, total_page + 1))[:2]:
            data = meta.get("data")
            data['page'] = str(page)
            url = meta.get('url')
            # temp_url = url + urllib.parse.urlencode(data)
            self.logger.info(f"{total_page} 开始爬取 第 {page} 页 data: {data}")
            yield self.FormRequest(
                response.url,
                formdata=data,
                method="POST",
                callback=self.parse_list,
                dont_filter=True,
                meta=meta
            )

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = item['publish_date'] or response.xpath("""string(//meta[@name='PubDate']/@content)""").get() or response.xpath(
            "//*[@class='fbrq']/text()").get()
        if item['publish_date']:
            item['publish_date'] = item['publish_date'].split(" ")[0]
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl fujian_ningde_was_policy -a get_next=0".split())
